import React, { useState, useEffect } from 'react';
import { Select, Spin } from 'antd';
import styled from 'styled-components';
import { suiteService } from '@/flowService';

const SelectOptionEmpty = styled.div`
  display: flex;
  height: 120px;
  align-items: center;
  justify-content: center;
`;

const SuiteSelect = ({ value, onChange, auto }) => {
  const [suiteList, setSuiteList] = useState([]);
  const [suiteLoading, setSuiteLoading] = useState(false);
  const [suiteLoaded, setSuiteLoaded] = useState(false);

  useEffect(() => {
    if (auto) {
      loadData();
    }
  }, [auto]);

  const loadData = async () => {
    setSuiteLoading(true);
    const res = await suiteService.querySuiteList();
    if (res.success) {
      setSuiteList(res.result.map(item => ({ label: item.suiteName, value: item.id })));
    }
    setSuiteLoaded(true);
    setSuiteLoading(false);
  };

  const handleVisibleChange = (visible) => {
    if (suiteLoaded) {
      return;
    }
    if (visible) {
      loadData();
    }
  };

  const handleChange = (val) => {
    onChange?.(val);
  };

  return (
    <Select
      value={value}
      placeholder="请选择套件"
      style={{ width: '100%' }}
      showSearch
      onDropdownVisibleChange={handleVisibleChange}
      onChange={handleChange}
      notFoundContent={
        <SelectOptionEmpty>
          {suiteLoading ? <Spin /> : <span>无数据</span>}
        </SelectOptionEmpty>
      }
    >
      {suiteList.map(item => (
        <Select.Option key={item.value} value={item.value}>
          {item.label}
        </Select.Option>
      ))}
    </Select>
  );
};

export default SuiteSelect; 